//
//  CZPhotoBrowserViewController.swift
//  GZWeibo666
//
//  Created by Apple on 15/12/7.
//  Copyright © 2015年 wdd. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZPhotoBrowserViewController: UIViewController {
    
    // MARK: - 属性
    // 控制器需要知道小图的图片.和frame
    /// 大图的URLs
//    private var urls: [NSURL]
    private var photoBrowserModels: [CZPhotoBrowserModel]
    
    /// 点击的cell indexPath
    private var indexPath: NSIndexPath
    
    /// cell重用标示
    private let PhotoBrowserReuseIdentifier = "PhotoBrowserReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("CZPhotoBrowserViewController deinit")
    }
    
    init(models: [CZPhotoBrowserModel], indexPath: NSIndexPath) {
        self.photoBrowserModels = models
        self.indexPath = indexPath
        super.init(nibName: nil, bundle: nil)
    }

    
    /// 流水布局
    private var layout = UICollectionViewFlowLayout()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.clearColor()

        prepareUI()
        
        // 设置页码
        pageLabel.text = "\(indexPath.item + 1) / \(photoBrowserModels.count)"
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 滚动到对应的图片
//        print("滚动到对应的图片: \(indexPath.item),collectionView:\(collectionView)")
        let newIndexPath = NSIndexPath(forItem: indexPath.item, inSection: 0)
        collectionView.scrollToItemAtIndexPath(newIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
//    override func viewDidAppear(animated: Bool) {
//        UIView.setAnimationsEnabled(false)
//        // 滚动到对应的图片
//        print("滚动到对应的图片: \(indexPath.item)")
//        collectionView.selectItemAtIndexPath(NSIndexPath(forItem: indexPath.item, inSection: 0), animated: false, scrollPosition: UICollectionViewScrollPosition.CenteredHorizontally)
//    }
    
    // MARK: - 按钮点击事件
    /// 关闭控制器
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 保存图片
    func save() {
        // 获取正在显示的cell的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        
        // 获取正在显示的照片
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CZPhotoBrowserCell
        if let image = cell.imageView.image {
            // 保存起来
            // completionTarget: 保存照片的回调者
            // completionSelector: 保存照片的回调方法,不能自己定义,到头文件查看
            // contextInfo: 上下文
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        } else {
            SVProgressHUD.showErrorWithStatus("没有图片")
        }
    }
    
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存图片失败")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存图片成功")
        }
    }
    
    private func prepareCollectionView() {
        // 设置collectionView背景颜色
        collectionView.backgroundColor = UIColor.clearColor()
        
        // 设置数据源
        collectionView.dataSource = self
        
        // 设置代理
        collectionView.delegate = self
        
        // 注册cell
        collectionView.registerClass(CZPhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserReuseIdentifier)
        
        // 设置layout
        layout.itemSize = view.bounds.size
        
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 不要弹簧效果
        collectionView.bounces = false
        
        // 分页
        collectionView.pagingEnabled = true
        
        // 不要间距
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        
        // 设置collectionView右边的内边距,collectionView的宽度比屏幕的宽度大10，不设置边距,最后一个cell有一部份会超出屏幕,使用内边距将看不到的10顶过来
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
        
        collectionView.showsHorizontalScrollIndicator = false
    }
    
    // MARK: - 准备UI
    private func prepareUI() {
        prepareCollectionView()
        
        // 按钮添加点击事件
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 添加控件
        // 添加背景视图
        view.addSubview(bkgView)
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        view.addSubview(pageLabel)
        
        
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        bkgView.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["cv": collectionView, "cb": closeButton, "sb": saveButton]
        // collectionView, 填充父控件
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-(-10)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width + 10, height: view.frame.height)
        
        // 页码
        // 水平方向
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        // 垂直方向        
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 25))
        
        // 关闭/保存按钮 水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // 关闭按钮垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // 保存按钮垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // 背景视图,填充父控件
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bv" : bkgView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bv" : bkgView]))
    }
    
    // MARK: - 懒加载控件
    /// collectionView
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = UIButton(bkgImageName: "health_button_orange_line", title: "关闭", font: 14)
    
    /// 保存按钮
    private lazy var saveButton: UIButton = UIButton(bkgImageName: "health_button_orange_line", title: "保存", font: 14)
    
    /// 页码
    private lazy var pageLabel = UILabel(color: UIColor.whiteColor(), fontSize: 14)
    
    /// 背景,当缩放imageView时,会改变alpha值
    private lazy var bkgView: UIView = {
        let view = UIView()
        
        // 设置背景
        view.backgroundColor = UIColor.blackColor()
        
        return view
    }()
}

// MARK: - 扩展
extension CZPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    /// 返回collectionView cell的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoBrowserModels.count
    }
    
    /// 返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserReuseIdentifier, forIndexPath: indexPath) as! CZPhotoBrowserCell
        
        cell.backgroundColor = UIColor.clearColor()
        
        // 设置cell的url
        cell.url = photoBrowserModels[indexPath.item].url
        
        // 设置cell的代理
        cell.delegate = self
        
        return cell
    }
    
    // 滚动停止的时候来判断页码
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取正在显示的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        
        // 设置页码
        pageLabel.text = "\(indexPath.item + 1) / \(photoBrowserModels.count)"
    }
}

// 扩展 CZPhotoBrowserViewController 实现 CZPhotoBrowserCellDelegate 协议
extension CZPhotoBrowserViewController: CZPhotoBrowserCellDelegate {
    /// 返回一个view让cell去根据图片缩放比例设置alpha
    func viewForTransparent() -> UIView {
        return bkgView
    }
    
    func photoBrowserCellDismissController() {
        // 直接关闭控制器
        close()
    }
    
    /// 返回缩放后的缩略位置
    func photoBrowserCellDismissTargetRect() -> CGRect {
        return dismissTargetRect()
    }
}

// 扩展 CZPhotoBrowserViewController 实现 转场协议
extension CZPhotoBrowserViewController: UIViewControllerTransitioningDelegate {
    
    // 返回 控制 modal时的动画 对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 返回控制 modal时的动画 对象
        return CZPhotoBrowserModalAnimation()
    }
    
    // 返回 控制 dismiss时的动画 对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CZPhotoBrowserDismissAnimation()
    }
}

// MARK: - 转场动画相关
extension CZPhotoBrowserViewController {
    /// 提供转场动画的过渡视图
    func modalTempImageView() -> UIImageView {
        // 需要获取到点击小图对应的模型
        let model = photoBrowserModels[indexPath.item]
        
        // 获取到小图的图片
        let imageView = model.imageView
        
        // 创建过渡视图
        let tempImageView = UIImageView(image: imageView.image)
        
        // 转换坐标系
        // imageView.superview? 转换前的坐标系
        // convertRect转换CGRect
        // rect: 要转换的CGRect
        // toCoordinateSpace: 转换后的坐标系
        let rect = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        
        // 设置过渡视图的frame
        tempImageView.frame = rect
        
        // 设置缩放模式
        tempImageView.contentMode = imageView.contentMode
        tempImageView.clipsToBounds = true
        
        return tempImageView
    }
    
    /// 计算大图的位置
    /// 大图和小图的比例是一样的.拿小图来计算也可以
    func moadalTargetFrame() -> CGRect {
        // 需要获取到点击小图对应的模型
        let model = photoBrowserModels[indexPath.item]
        
        // 获取小图
        // 不能强制拆包
        if let image = model.imageView.image {
            // 等比例缩放到宽度等于屏幕宽度
            let newWidht = UIScreen.width()
            var newHeight = newWidht * image.size.height / image.size.width
            
            var offestY: CGFloat = 0
            // 判断是长图还是短图
            if newHeight < UIScreen.height() {
                offestY = (UIScreen.height() - newHeight) * 0.5
            } else {
                // 图片太长,放大不好看,只有屏幕的高度
                newHeight = UIScreen.height()
            }
            return CGRect(x: 0, y: offestY, width: newWidht, height: newHeight)
        } else {
            return CGRectZero
        }
    }
    
    // MARK: 关闭动画
    func dismissTempImageView() -> UIImageView {
        // 正在显示的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        
        // 正在显示的cell
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CZPhotoBrowserCell
        
        // 正在显示的大图
        let imageView = cell.imageView
        
        // 创建过渡视图
        let tempImageView = UIImageView(image: imageView.image)
        
        // 坐标系转换
        let rect = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        
        // 设置frame
        tempImageView.frame = rect
        
        // 设置缩放模式
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        
        return tempImageView
    }
    
    /// dismiss最终缩放位置
    func dismissTargetRect() -> CGRect {
        // 正在显示的cellindexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last
        
        // 拿到对应的模型
        let model = photoBrowserModels[indexPath!.item]
        
        // 转换坐标系
        let rect = model.imageView.convertRect(model.imageView.frame, toCoordinateSpace: view)
        
        return rect
    }
}